package org.grow.stable.security.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Entity
@ToString
@Setter
public class User implements UserDetails {
    @Id
    private String username;
    private String password;
    private String nickname;
    private Integer batch = 1;
    @ElementCollection(fetch = FetchType.EAGER)
    //表名字 共三列 一列是关联的username 一列是List<String>中的string 一列是可有可无的List_index
    @JoinTable(name = "user_role",joinColumns = {
            @JoinColumn(name = "username_fk",referencedColumnName = "username")
    })
   // @JoinTable
    //@OrderColumn(name = "role_index")
    @Column(name = "role")
    @Enumerated(EnumType.STRING)
    private List<Role> roles;


    public List<Role> getRoles() {

        return roles;
    }

    public String getNickname() {
        return nickname;
    }

    public Integer getBatch() {
        return batch;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream().map(x->{

            return new SimpleGrantedAuthority(x.toString());
        })
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
